package com.zspringboot.demo.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.zspringboot.demo.entity.User;
import com.zspringboot.demo.service.IUserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 生成Token
 * @program: springboot2
 * @description:
 * @author: LaoLang
 * @create: 2024-02-19 14:20
 * @version:1.0
 **/
@Component
public class TokenUtils {

    private static IUserService staticUserService;

    @Resource
    private IUserService iUserService;

    @PostConstruct
    public void setUserService(){
        staticUserService = iUserService;
    }
    /**
     * 生成Token
     * @param userId
     * @param sign
     * @return
     */
    public static String genToken(String userId, String sign){
        return JWT.create().withAudience(userId) // 将 user id 保存到 token 里面
                .withExpiresAt(DateUtil.offsetHour(new Date(),2)) //五分钟后token过期
                .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥

    }

    /**
     * 获取当前登录的用户信息
     */
    public static User getCurrentUser(){
        try {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if (StrUtil.isNotBlank(token)){
            String userId = JWT.decode(token).getAudience().get(0);
            return staticUserService.getById(userId);
        }
            }catch (Exception e){
                return null;
            }
        return null;
    }

}
